<!-- 供应商管理-供应商认证列表（员工）  -->
<template>
  <div>
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    </pageHeader>
    <div class="search-box">
      <a-space>
        <div>
          <a-input-group>
            <a-select
              :style="{ width: '120px' }"
              placeholder="请选择"
              v-model="currSelectVal"
              ><a-option value="number">供应商编号</a-option>
              <a-option value="name">供应商名称</a-option>
            </a-select>
            <a-input-search
              :style="{ width: 'auto' }"
              placeholder="请输入"
              v-model="currSelectSearch"
              search-button
              @search="search"
            />
          </a-input-group>
        </div>
      </a-space>
      <div>
        <a-space>
          <a-button type="outline" @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            <template #default>重置</template>
          </a-button>
          <a-button status="success">
            <template #icon>
              <icon-download />
            </template>
            <template #default>导入</template>
          </a-button>

          <a-button status="warning">
            <template #icon>
              <icon-export rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>
        </a-space>
      </div>
    </div>
    <div style="padding: 10px">
      <tableTurn :tableData="getData" :args="args" ref="tableTurnRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          v-for="(item, index) in selectedHeader"
          :title="item.title"
          :key="index"
          :data-index="item.code"
          align="center"
          :width="200"
        >
          <template v-if="item.code === 'beginTimes'" #cell="{ record }">
            {{ dayjs(record.taskReleasTime).format('YYYY-MM-DD') }}
          </template>
          <template v-else-if="item.code === 'endTimes'" #cell="{ record }">
            {{
              record.endTime ? dayjs(record.endTime).format('YYYY-MM-DD') : '无'
            }}
          </template>
          <!-- 认证项目item -->
          <template v-else-if="item.code === 'auth'" #cell="{ record }">
            <div
              class="aunt-item"
              :class="
                record.state === 2
                  ? 'Qualified'
                  : record.state === 3
                  ? 'Examining'
                  : record.state === 4
                  ? 'Pass'
                  : record.state === 5
                  ? 'NoPass'
                  : 'Qualified'
              "
            >
              <div>
                {{ record.aunt.authSetName }}
              </div>
            </div>
          </template>
          <!-- 执行状态item -->
          <template
            v-else-if="item.code === 'ExecutionStatus'"
            #cell="{ record }"
          >
            <div>
              <a-space>
                <div
                  class="state-item"
                  :class="
                    record.state === 2
                      ? 'StateQualified'
                      : record.state === 3
                      ? 'StateExamining'
                      : record.state === 4
                      ? 'StatePass'
                      : record.state === 5
                      ? 'StateNoPass'
                      : 'StateQualified'
                  "
                >
                  <!-- <a-typography-text type="primary">
                  {{
                    record.aunt.state === 4
                      ? '通知整改'
                      : record.aunt.state === 5
                      ? '通知整改'
                      : ''
                  }}
                </a-typography-text> -->
                </div>
                <span
                  :style="{
                    color:
                      record.state === 2
                        ? '#ff9a2e'
                        : record.state === 3
                        ? '#165dff'
                        : record.state === 4
                        ? '#31c27c'
                        : record.state === 5
                        ? '#f53f3f'
                        : '#ff9a2e',
                  }"
                  >{{
                    record.state === 2
                      ? '待执行'
                      : record.state === 3
                      ? '执行中'
                      : record.state === 4
                      ? '认证通过'
                      : record.state === 5
                      ? '认证不通过'
                      : '待执行'
                  }}</span
                >
              </a-space>
            </div>
          </template>
        </a-table-column>

        <!-- 操作item -->
        <a-table-column align="center" :width="300" fixed="right" title="操作">
          <template #cell="{ record }">
            <div v-if="record.state === 2">
              <a-button
                type="primary"
                status="success"
                @click="
                  jump(
                    record,
                    record.id,
                    record.authSetName === '样品检测类' ? 1 : 2
                  )
                "
                >执行</a-button
              >
            </div>
            <div v-else-if="record.state === 3">
              <a-button
                type="text"
                @click="
                  jump(
                    record,
                    record.id,
                    record.authSetName === '样品检测类' ? 1 : 2
                  )
                "
                >提交认证</a-button
              >
            </div>
            <div v-else-if="record.state === 4 || record.state === 5">
              <a-button
                type="text"
                @click="
                  jump(
                    record,
                    record.id,
                    record.authSetName === '样品检测类' ? 1 : 2
                  )
                "
                >认证详情</a-button
              >
            </div>
          </template>
        </a-table-column>
      </tableTurn>
    </div>
    <AddAUNT v-model:visible="ModelVisible" @addProject="addProject"></AddAUNT>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import {
    GetSupplierLevelInfo,
    addSupplierauth,
  } from '@/api/buy-management/supplier-management/base-setting';
  import {
    getSupplierStaffList,
    putSupplierAuth,
  } from '@/api/buy-management/supplier-management/supplier-certification/index';
  import {
    GetSupplierPrimaryList,
    DelSupplierPrimaryList,
    GetSupplierPrimaryHeaderList,
    PutSupplierPrimaryHeaderList,
  } from '@/api/buy-management/supplier-management/supplier-primary-list';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import { formHeaderSetting } from '@/types/global';

  const router = useRouter();
  const authSetTypeText = ref();
  const title = '供应商认证列表（员工）';
  const breadCrumb = ['采购管理', '供应商管理', '供应商认证列表（员工）'];

  const headerSetting = reactive<formHeaderSetting>({
    list: [],
  });

  const ModelVisible = ref(false);

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (销售员)

  // 表格配置
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  let tableTurnRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  let currNameSearch = ref(''); // 储存搜索供应商名称的值
  let isFirstSelect = ref(true);
  let UserInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      const res = await getSupplierStaffList({
        ...pageData,
        userId: UserInfo.id,
        [currSelectVal.value]: isFirstSelect.value
          ? undefined
          : currSelectSearch.value,
      });
      isFirstSelect.value = false;

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let levelList = reactive<any>({
    list: [],
  });

  const getLevelData = async () => {
    try {
      const { data } = await GetSupplierLevelInfo();
      levelList.list = data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getLevelData();

  // 搜索按钮
  const search = () => {
    tableTurnRef.value.loadData();
  };
  // 重置按钮
  const reset = () => {
    currSelectSearch.value = '';
    currSelectVal.value = '';
    tableTurnRef.value.loadData();
  };

  const addautn = () => {
    ModelVisible.value = true;
  };

  const addProject = async (formData, date, content, key) => {
    if (key === 1) {
      await addSupplierauth({
        id: formData.id,
        submitDemandTime: date,
        flowStr: content,
      });
    } else {
      await addSupplierauth({
        id: formData.id,
        submitDemandTime: date,
        flowStr: `${content}`,
      });
    }
  };

  // const add

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableTurnRef.value.loadData();
    }
  };

  onMounted(() => {
    // 监听键盘事件
    window.addEventListener('keydown', keyDown);
  });

  const jump = (e: any, authId: any, type: any) => {
    if (e.authSetType === 1 || e.authSetType === 3) {
      router.push({
        name: 'StaffSampling',
        query: { gys: e.supplierId, auth: authId, type },
      });
    } else if (e.authSetType === 2) {
      router.push({
        name: 'StaffFieldCertification',
        query: { gys: e.supplierId, auth: authId },
      });
    }
  };

  const columns = [
    {
      id: 2,
      title: '供应商编号',
      visible: true,
      type: 'string',
      code: 'supplierNumber',
    },
    {
      id: 3,
      title: '供应商名称',
      visible: true,
      type: 'string',
      code: 'supplierName',
    },
    {
      id: 4,
      title: '供应商等级',
      visible: true,
      type: 'string',
      code: 'supplierLevel',
    },
    {
      id: 6,
      title: '任务下单人',
      visible: true,
      type: 'string',
      code: 'taskReleaserName',
    },
    {
      id: 7,
      title: '任务开始时间',
      visible: true,
      type: 'string',
      code: 'beginTimes',
    },

    {
      id: 9,
      title: '认证项目',
      visible: true,
      type: 'string',
      code: 'authSetName',
    },
    {
      id: 10,
      title: '执行状态',
      visible: true,
      type: 'string',
      code: 'ExecutionStatus',
    },
  ];

  const selectedHeader = computed(() => {
    return columns.filter((item) => item.visible);
  });

  let currId = ref(-1); // 储存当前选中的id

  // 去往对应的详情页面
  const goDetail = (id: number) => {
    router.push({
      name: 'ArchivalInformation',
      query: {
        id,
        type: 1,
      },
    });
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await DelSupplierPrimaryList({
        id,
      });
      tableTurnRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const fulfil = async (data) => {
    data.state = 3;
    await putSupplierAuth(data);
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
    margin-top: -7px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .auntContent {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .aunt-item {
    width: 100px;
    height: 40px;
    line-height: 40px;
    border: 1px solid rgba(229, 230, 235);
    border-radius: 5px;
  }

  .state-item {
    width: 16px;
    height: 16px;
    border: 1px solid red;
    border-radius: 100%;
  }
  .Examining {
    // 执行中
    background: rgb(216, 229, 255);
    color: #165dff;
    border: none;
  }
  .Pass {
    // 已通过
    background-color: rgba(49, 194, 124);
    color: #31c27c;
    border: none;
  }
  .NoPass {
    //不通过
    background: #f53f3f;
    border: none;
  }
  .Qualified {
    // 待执行
    background: rgba(255, 247, 232);
    border: none;
    color: #ff9a2e;
  }

  .StateExamining {
    // 执行中
    background-color: #165dff;
    border: none;
  }
  .StatePass {
    // 已通过
    background-color: rgba(49, 194, 124);
    color: rgba(49, 194, 124);
    border: none;
  }
  .StateNoPass {
    //不通过
    background-color: #f53f3f;
    border: none;
  }
  .StateQualified {
    // 待执行
    background-color: #ff9a2e;
    border: none;
    color: #ff9a2e;
  }
</style>
